from django.conf import settings
from itsdangerous import Serializer, BadData

from . import constants_oauth


def generate_access_token(openid):
    """
    签名openid
    :param openid: 用户的openid
    :return: access_token
    """
    serializer = Serializer(settings.SECRET_KEY, expires_in=constants_oauth.ACCESS_TOKEN_EXPIRES)
    data = {'openid': openid}
    token = serializer.dumps(data)

    return token.decode()


def check_access_token(access_token):
    """
    反解： 反序列化
    :param access_token : openid 密文
    :return openid 明文
    """

    serializer = Serializer(settings.dev.SECRET_KEY, expires_in=constants_oauth.ACCESS_TOKEN_EXPIRES)

    try:
        data = serializer.loads(access_token)
    except BadData:
        return None
    else:
        return data.get('openid')
